﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;

namespace HashFoo.Rest.Server
{
    /// <summary>
    /// Utility and extension functions for <see cref="IServiceHandler{TRequest}"/>.
    /// </summary>
    public static class ServiceHandlerUtil
    {
        /// <summary>
        /// Get all the <see cref="IServiceHandler{TRequest}"/> interfaces that a type implements.
        /// </summary>
        /// <remarks>
        /// This should usually only be one type, but will look for multiples just in case.
        /// </remarks>
        /// <param name="handlerType"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetServiceHanlderInterfaces(Type handlerType)
        {
            return handlerType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IServiceHandler<>));
        }

        /// <summary>
        /// Get the concrete service handler implementation types in an assembly.
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static IEnumerable<Type> GetServiceHandlerImplementations(Assembly assembly)
        {
            return assembly.GetTypes()
                .Where(t =>
                       t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IServiceHandler<>)) &&
                       t.IsClass &&
                       t.IsAbstract == false);
        }
    }
}